"""
五子棋游戏数据库模型

定义与五子棋游戏相关的数据库模型，包括游戏、游戏动作等。
"""

import enum
from datetime import datetime
from typing import List, Optional

from sqlalchemy import Column, String, Integer, ForeignKey, DateTime, Enum, Text, Boolean
from sqlalchemy.orm import relationship

from app.db.base import Base, TimestampMixin


class PlayerColor(str, enum.Enum):
    """玩家棋子颜色枚举"""
    BLACK = "black"
    WHITE = "white"


class GameStatus(str, enum.Enum):
    """游戏状态枚举"""
    WAITING = "waiting"    # 等待玩家加入
    ONGOING = "ongoing"    # 游戏进行中
    COMPLETED = "completed"  # 游戏已完成
    ABORTED = "aborted"    # 游戏已中止


class Game(Base, TimestampMixin):
    """五子棋游戏模型"""
    
    # 游戏信息
    board_size = Column(Integer, default=15, nullable=False)
    board_state = Column(Text, nullable=False)  # JSON格式的棋盘状态
    status = Column(Enum(GameStatus), default=GameStatus.WAITING, nullable=False)
    
    # 玩家信息
    player1_id = Column(Integer, ForeignKey("user.id"), nullable=False)
    player2_id = Column(Integer, ForeignKey("user.id"), nullable=True)
    player1_color = Column(Enum(PlayerColor), nullable=True)
    player2_color = Column(Enum(PlayerColor), nullable=True)
    current_turn = Column(Enum(PlayerColor), nullable=True)
    
    # 游戏结果
    winner_id = Column(Integer, ForeignKey("user.id"), nullable=True)
    is_draw = Column(Boolean, default=False, nullable=False)
    
    # 时间戳
    started_at = Column(DateTime, nullable=True)
    ended_at = Column(DateTime, nullable=True)
    
    # 关系
    player1 = relationship("User", foreign_keys=[player1_id], backref="games_as_player1")
    player2 = relationship("User", foreign_keys=[player2_id], backref="games_as_player2")
    winner = relationship("User", foreign_keys=[winner_id], backref="games_won")
    moves = relationship("GameMove", back_populates="game", cascade="all, delete-orphan")
    
    __tablename__ = "gomoku_game"


class GameMove(Base, TimestampMixin):
    """五子棋游戏动作模型"""
    
    # 关联的游戏
    game_id = Column(Integer, ForeignKey("gomoku_game.id"), nullable=False)
    
    # 落子信息
    user_id = Column(Integer, ForeignKey("user.id"), nullable=False)
    x = Column(Integer, nullable=False)
    y = Column(Integer, nullable=False)
    color = Column(Enum(PlayerColor), nullable=False)
    move_number = Column(Integer, nullable=False)
    
    # 关系
    game = relationship("Game", back_populates="moves")
    user = relationship("User", backref="game_moves")
    
    __tablename__ = "gomoku_game_move" 